<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="流程定义标识" prop="processDefinitionKey">
        <el-input
          v-model="queryParams.processDefinitionKey"
          placeholder="请输流程定义标识"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['flowable:bpmProcessInstance:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bpmProcessInstanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="流程实例id" align="center" prop="processInstanceId" v-if="true" :show-overflow-tooltip="true"/>
      <el-table-column label="流程定义名称" align="center" prop="processInstanceName" :show-overflow-tooltip="true"/>
      <el-table-column label="流程定义key" align="center" prop="processDefinitionKey"  :show-overflow-tooltip="true"/>
      <el-table-column label="流程定义版本" align="center" prop="processDefinitionVersion" />
      <el-table-column label="流程发起人ID" align="center" prop="startUserId" />
      <el-table-column label="流程发起人" align="center" prop="startUserNickName" />
      <el-table-column label="流程启动时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="当前办理人" align="center" prop="currAssignee" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['flowable:bpmProcessInstance:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleInfo(scope.row)"
            v-hasPermi="['flowable:bpmProcessInstance:edit']"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改流程实例对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-table v-loading="loading" :data="processDefinitionList" @selection-change="handleSelectionChange">
        <el-table-column label="流程定义名称" align="center" prop="processDefinitionName" />
        <el-table-column label="流程定义标识" align="center" prop="processDefinitionKey" />
        <el-table-column label="流程xml名称" align="center" prop="xmlName" />
        <el-table-column label="流程部署时间" align="center" prop="processDeploymentTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.processDeploymentTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              :loading="startLoading"
              @click="handleStartProcessInstance(scope.row)"
            >发起流程</el-button>
          </template>
        </el-table-column>
      </el-table>


      <pagination
        v-show="defineTotal>0"
        :total="defineTotal"
        :page.sync="defineQueryParams.pageNum"
        :limit.sync="defineQueryParams.pageSize"
        @pagination="getDefinitionList"
      />
    </el-dialog>

    <!-- 添加或修改流程实例对话框 -->
    <el-dialog :title="title" :visible.sync="submitDialog" width="70%" append-to-body>
      <div>
        <instance-approval ref="insApp" :form-create-info="formCreateInfo" :task-approval-form="taskApprovalForm" @complete="handleConfirm" @selectApprover="selectApprover"></instance-approval>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBpmProcessInstance,
  getBpmProcessInstance,
  addBpmProcessInstance,
  updateBpmProcessInstance, deleteProcessInstance,
} from "@/api/flowable/bpmProcessInstance";
import { listProcessDefinition} from "@/api/flowable/processDefinition";
import { complete } from "@/api/flowable/bpmTask";
import formCreate from "@form-create/element-ui";
import InstanceApproval from "@/views/flowable/bpmProcessInstance/instanceApproval.vue";
import Approval from "@/views/flowable/bpmProcessDetail/approval.vue";
import DynamicComponent from "@/components/DynamicComponent/dynamicComponent.vue";

export default {
  name: "BpmProcessInstance",
  components: {DynamicComponent, Approval, InstanceApproval},
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //流程定义条数
      defineTotal:0,
      // 流程实例表格数据
      bpmProcessInstanceList: [],
      //流程定义列表
      processDefinitionList:[],
      // 流程定义设置表格数据
      bpmTaskAssigneeVo: [],
      //审批弹出层
      submitDialog:false,
      //节点ID
      firstTaskId:'',
      startLoading:false,
      //流程审批提交信息
      taskApprovalForm:{
        formDate:'',
        flowData:{
          assignee:null,
          comment:null,
        }
      },

      //流程表单信息
      formCreateInfo:{
        formCustomCreatePath:'',
        formType:0,
        option: {},
        rule:[],
        value: {}
      },
      fApi: {},



      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        processInstanceName: undefined,
        processDefinitionKey: undefined,
        processDefinitionVersion: undefined,
        startUserId: undefined,
        startUserNickName: undefined,
        processInstanceState: undefined,
        businessKey: undefined,
        startTime: undefined,
        currAssignee: undefined,
        currAssigneeId: undefined,
        actBusinessStatus: undefined
      },
      defineQueryParams:{
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        processInstanceId: [
          { required: true, message: "流程实例id不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询流程实例列表 */
    getList() {
      this.loading = true;
      listBpmProcessInstance(this.queryParams).then(response => {
        this.bpmProcessInstanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDefinitionList(){
      listProcessDefinition(this.defineQueryParams).then(response => {
        this.processDefinitionList = response.rows;
        this.defineTotal = response.total;
        this.open = true;
      });
    },
    // 表单重置
    reset() {
      this.form = {
        processInstanceId: undefined,
        processInstanceName: undefined,
        processDefinitionKey: undefined,
        processDefinitionVersion: undefined,
        startUserId: undefined,
        startUserNickName: undefined,
        processInstanceState: undefined,
        businessKey: undefined,
        startTime: undefined,
        currAssignee: undefined,
        currAssigneeId: undefined,
        actBusinessStatus: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.processInstanceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      listProcessDefinition(this.defineQueryParams).then(response => {
          //todo 分页查询
        this.processDefinitionList = response.rows;
        this.defineTotal = response.total;
        this.open = true;
      });
      this.title = "添加流程实例";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.processInstanceId != null) {
            updateBpmProcessInstance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addBpmProcessInstance(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除流程实例为"' + row.processInstanceName + '"的数据项？').then(() => {
        this.loading = true;
        return deleteProcessInstance(row.processInstanceId);
      }).then(() => {
        this.loading = false;
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /**
     * 流程实例详细信息
     * @param row
     */
    handleInfo(row){
      this.$router.push({
        name:'bpmnProcessDetail',
        query:{
          processInstanceId:row.processInstanceId
        }
      })


    },
    /**
     * 创建流程实例
     * @param row
     */
    handleStartProcessInstance(row){
      this.startLoading = true;
      addBpmProcessInstance({processDefinitionId:row.id}).then((res)=>{
        this.bpmTaskAssigneeVo = res.data.bpmTaskAssigneeVo;
        this.firstTaskId =res.data.taskId;
        this.formCreateInfo.formType = this.bpmTaskAssigneeVo.formType
        this.open = false;
        if(this.bpmTaskAssigneeVo.formType==='0'){
          this.formCreateInfo.option = JSON.parse(this.bpmTaskAssigneeVo.formOption)
          this.formCreateInfo.rule = formCreate.parseJson(this.bpmTaskAssigneeVo.formFields)
        }else {
          this.formCreateInfo.formCustomCreatePath = this.bpmTaskAssigneeVo.formCustomCreatePath;
        }
        this.startLoading = false;
        this.submitDialog = true;
      })
    },
    // 提交审批
    handleConfirm(){
      let taskApprovalForm = {
        taskId: this.firstTaskId,
        formOption:this.bpmTaskAssigneeVo.formOption,
        formFields:this.bpmTaskAssigneeVo.formFields,
        formVariables:JSON.stringify(this.formCreateInfo.value),
        formCustomCreatePath:this.bpmTaskAssigneeVo.formCustomCreatePath,
        formType:this.bpmTaskAssigneeVo.formType,
        formDate: '',
        flowData: {
          assignee: this.taskApprovalForm.flowData.assignee,
          comment: '开始流程',
        }
      }
      this.$refs.insApp.buttonLoading = true;
      complete(taskApprovalForm).then((res)=>{
        this.$message.success("提交成功");
        this.$refs.insApp.buttonLoading = true;
        this.submitDialog = false;
        this.getList();
      })
    },
    close(){
      this.submitDialog = false;
    },
    //选择审批人员
    selectApprover(val){
      if(val&&val.length>0){
        this.taskApprovalForm.flowData.assignee=val[0].userId
        this.taskApprovalForm.flowData.assigneeName=val[0].nickName
      }
    },
  }
};
</script>
